<script setup lang="ts">
import { ref, onMounted } from 'vue'
import type { addDepartments, SimpleUser, depts } from '@/types/departments'
import { getSimpleUserListApi, addDepartmentsApi, getDepartmentsDetailApi, updateDepartmentsApi } from '@/api/departments'
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import { nextTick } from 'vue'

// 弹层显示和隐藏
const dialogVisible = ref(false)
// 定义dialog输入框数据
const formData = ref<addDepartments>({
  code: '',
  introduce: '',
  manager: '',
  name: '',
  pid: '',
  id: '',
  createTime: ''
})
// 控制title
const title = ref('')

// 打开弹层
const openDialog = async (type: 'edit' | 'add') => {
  dialogVisible.value = true
  // 需要nextick 因为弹层是异步渲染
  await nextTick()
  if (type === 'add') {
    return (title.value = '新增部门')
  }
  await getDeptsDetail()
  title.value = '编辑部门'
}

// 获取部门详情 回显表单数据
const getDeptsDetail = async () => {
  const res = await getDepartmentsDetailApi(props.nodeData?.id!)
  formData.value = res.data
}
// 关闭弹层
const closeDialog = () => {
  dialogVisible.value = false
  // 重置表单
  formRef.value?.resetFields()
  // 清空数据
  formData.value = {
    code: '',
    introduce: '',
    manager: '',
    name: '',
    pid: '',
    id: '',
    createTime: ''
  }
}

// 获取用户列表
const userList = ref<SimpleUser[]>([])
const getUserList = async () => {
  // 获取用户列表
  const res = await getSimpleUserListApi()
  userList.value = res.data
}
onMounted(() => {
  getUserList()
})

//表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入部门名称', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入部门编码', trigger: 'blur' },
    { min: 1, max: 10, message: '长度在 1 到 10 个字符', trigger: 'blur' }
  ],
  manager: [{ required: true, message: '请选择部门负责人', trigger: 'change' }],
  introduce: [
    { required: true, message: '请输入部门介绍', trigger: 'blur' },
    { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }
  ]
}

// 点击确定按钮
// 子组件获取父组件点击那一行的数据
// 接收父组件传递过来的数据
type Props = {
  nodeData?: depts
}
const props = defineProps<Props>()
// 子组件向父组件传递数据
type Emits = {
  (e: 'updataList'): void
}
const emits = defineEmits<Emits>()
const formRef = ref<FormInstance | null>(null)
const submit = () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (!valid) return
    // 写! 表示不能为空
    formData.value.pid = props.nodeData?.id!
    // 判断 是添加逻辑 还是 编辑逻辑
    if (title.value === '新增部门') {
      await addDepartmentsApi(formData.value)
    } else {
      await updateDepartmentsApi(formData.value)
    }
    // 关闭弹层 + 清空数据列表
    closeDialog()
    // 重新渲染 调用父组件方法
    emits('updataList')
    // 提示用户
    ElMessage.success('新增成功')
  })
}

// 暴露 openDialog方法
defineExpose({
  openDialog,
  submit
})
</script>
<template>
  <div class="add-dept">
    <!-- 放置弹层组件 -->
    <el-dialog :title="title" v-model="dialogVisible">
      <!-- 表单组件  el-form   label-width设置label的宽度   -->
      <!-- 匿名插槽 -->
      <el-form label-width="120px" ref="formRef" :model="formData" :rules="rules">
        <el-form-item label="部门名称" prop="name">
          <el-input style="width: 80%" placeholder="1-10个字符" v-model="formData.name" />
        </el-form-item>
        <el-form-item label="部门编码" prop="code">
          <el-input style="width: 80%" placeholder="1-10个字符" v-model="formData.code" />
        </el-form-item>
        <el-form-item label="部门负责人" prop="manager">
          <el-select style="width: 80%" placeholder="请选择" v-model="formData.manager">
            <el-option v-for="item in userList" :key="item.id" :value="item.username" :label="item.username"> </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门介绍" prop="introduce">
          <el-input style="width: 80%" placeholder="1-300个字符" type="textarea" :rows="3" v-model="formData.introduce" />
        </el-form-item>
      </el-form>
      <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
      <template #footer>
        <div>
          <el-button type="primary" @click="submit">确定</el-button>
          <el-button @click.prevent="closeDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style scoped></style>
